package com.xiaoxin.errorDemo.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebFilter(urlPatterns = "/filter/*", filterName = "loginFilter")
public class CustomFilter implements Filter {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    // /**
    //  * 容器加载时执行
    //  */
    // @Override
    // public void init(FilterConfig filterConfig) throws ServletException {
    //
    // }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String token = req.getHeader("token");
        // TODO 检查token
        if (StringUtils.isEmpty(token)) {
            Map<String, Object> outMap = new HashMap<>();
            outMap.put("msg", "token不能为空");
            // ↓转JSON
            String jsonStr = objectMapper.writeValueAsString(outMap);
            // 返回错误
            renderJson(resp, jsonStr);
        } else {
            // ↓放行
            chain.doFilter(request, response);
        }
    }

    /**
     * 返回数据
     */
    private void renderJson(HttpServletResponse response,String json) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        // 拿到输出流
        try(PrintWriter writer = response.getWriter()) {
            writer.print(json);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // /**
    //  * 容器销毁时执行
    //  */
    // @Override
    // public void destroy() {
    //
    // }
}
